package com.rfid.acs;




import com.rfid.acs.net.tcp.FiledId;
import com.rfid.acs.net.tcp.IRequest;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 文件名:AcsRequestBean
 * 创建者:mengqi.wang
 * 创建日期:2018\11\14 0014 13:53
 * 描述: TODO
 */
abstract class AcsRequestBean implements IRequest {

    @FiledId(name = "AY")
    public String checkNo = "1AZF05B";

    public AcsRequestBean() {
        command = requestCommand();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd    HHmmss");
        date = sdf.format(new Date());
    }

    protected abstract String requestCommand();

    public String command;

    public String date;

    private String splitSymbol = "|";

    @Override
    public String requestMessage() {
        StringBuffer buffer = new StringBuffer();

        if (command != null) {
            buffer.append(command);
        }

        buffer.append(dateBefore());

        if (date != null) {
            buffer.append(date);
        }

        buffer.append(dateAfter());

        buffer.append(splitSymbol);
        //添加字段
        Class<? extends AcsRequestBean> clazz = this.getClass();
        List<Field> fileds = getAllFileds(clazz);
        for (int i = 0; i < fileds.size(); i++) {
            Field field = fileds.get(i);
            FiledId annotation = field.getAnnotation(FiledId.class);
            if (annotation != null) {
                String name = annotation.name();
                try {
                    field.setAccessible(true);
                    Object value = field.get(this);
                    if (name != null) {
                        buffer.append(name);
                        if (value != null) {
                            buffer.append(value.toString());
                        }

                        buffer.append(splitSymbol);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        String result = buffer.toString();
        return result.endsWith(splitSymbol) ? result.substring(0, result.length() - 1) : result;
    }

    private List<Field> getAllFileds(Class<? extends AcsRequestBean> clazz) {
        List<Field> fieldList = new ArrayList<>();
        Field[] fields = clazz.getFields();
        Field[] declaredFields = clazz.getDeclaredFields();
        fieldList.addAll(Arrays.asList(fields));
        fieldList.addAll(Arrays.asList(declaredFields));
        return fieldList;
    }

    public String dateAfter() {
        return "";
    }

    public String dateBefore() {
        return "";
    }
}
